import 'package:flutter/material.dart';
import 'dart:async';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo - 智能计数器',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color.fromARGB(255, 168, 75, 211),
        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '20231120247-郑璐 '),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  int _counter = 0;
  double _progressValue = 0.0;
  bool _isAnimating = false;
  String _inputText = '';
  bool _switchValue = false;
  int _selectedIndex = 0;

  // 动画控制器
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  // 自动模式相关
  Timer? _autoTimer;
  int _autoInterval = 1; // 自动增加间隔（秒）

  final TextEditingController _textController = TextEditingController();
  final List<String> _counterHistory = [];

  @override
  void initState() {
    super.initState();
    // 动画控制器初始化
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(begin: 1.0, end: 1.2).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.elasticOut),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    _textController.dispose();
    _autoTimer?.cancel(); // 清理定时器
    super.dispose();
  }

  // 启动自动模式
  void _startAutoMode() {
    if (_autoTimer != null) return; // 防止重复启动

    _autoTimer = Timer.periodic(Duration(seconds: _autoInterval), (timer) {
      _incrementCounter();
      // 添加自动模式标记
      if (_counterHistory.isNotEmpty) {
        _counterHistory[_counterHistory.length - 1] += ' (自动)';
      }
    });

    setState(() {
      _counterHistory.add('自动模式已启动 - 每${_autoInterval}秒自动计数');
    });
  }

  // 停止自动模式
  void _stopAutoMode() {
    _autoTimer?.cancel();
    _autoTimer = null;

    setState(() {
      _counterHistory.add('自动模式已停止');
    });
  }

  // 切换自动模式
  void _toggleAutoMode(bool value) {
    setState(() {
      _switchValue = value;
    });

    if (value) {
      _startAutoMode();
    } else {
      _stopAutoMode();
    }
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
      _progressValue = (_counter % 10) / 10; // 进度条每10次重置
      _counterHistory.add(
        '计数: $_counter 时间: ${DateTime.now().toString().substring(11, 19)}',
      );
    });

    // 触发缩放动画
    _animationController.forward().then((_) {
      _animationController.reverse();
    });
  }

  void _decrementCounter() {
    setState(() {
      if (_counter > 0) {
        _counter--;
        _progressValue = (_counter % 10) / 10;
        _counterHistory.add(
          '减少: $_counter 时间: ${DateTime.now().toString().substring(11, 19)}',
        );
      }
    });
  }

  void _resetCounter() {
    setState(() {
      _counter = 0;
      _progressValue = 0.0;
      _counterHistory.clear();
      _counterHistory.add('重置计数器');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold( 
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        // 图片及ICON
        leading: const Icon(Icons.calculate),
        actions: [
          IconButton(icon: const Icon(Icons.refresh), onPressed: _resetCounter),
        ],
      ),

      body: SingleChildScrollView(
        //  SingleChildScrollView
        padding: const EdgeInsets.all(16.0), // 填充
        child: Column(
          // 线性布局(Column)
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 装饰容器
            DecoratedBox(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.purple.shade100, Colors.blue.shade100],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.3),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  children: [
                    //  文本及样式
                    Text(
                      '智能计数器',
                      style: Theme.of(
                        context,
                      ).textTheme.headlineMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                        color: Colors.purple.shade800,
                      ),
                    ),
                    const SizedBox(height: 16),

                    // 缩放动画
                    AnimatedBuilder(
                      animation: _scaleAnimation,
                      builder: (context, child) {
                        return Transform.scale(
                          //  变换
                          scale: _scaleAnimation.value,
                          child: Container(
                            // 容器组件
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(10),
                              border: Border.all(
                                color: Colors.purple.shade300,
                                width: 2,
                              ),
                            ),
                            child: Text(
                              '$_counter',
                              style: Theme.of(
                                context,
                              ).textTheme.displayLarge?.copyWith(
                                color: Colors.purple.shade700,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        );
                      },
                    ),

                    const SizedBox(height: 16),

                    // 进度指示器
                    Column(
                      children: [
                        Text(
                          '进度 (每10次循环):',
                          style: TextStyle(color: Colors.purple.shade700),
                        ),
                        const SizedBox(height: 8),
                        LinearProgressIndicator(
                          value: _progressValue,
                          backgroundColor: Colors.grey.shade300,
                          valueColor: AlwaysStoppedAnimation<Color>(
                            Colors.purple.shade600,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text('${(_progressValue * 100).toInt()}%'),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            // 线性布局(Row)
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // 按钮
                ElevatedButton.icon(
                  onPressed: _decrementCounter,
                  icon: const Icon(Icons.remove),
                  label: const Text('减少'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red.shade400,
                    foregroundColor: Colors.white,
                  ),
                ),

                ElevatedButton.icon(
                  onPressed: _incrementCounter,
                  icon: const Icon(Icons.add),
                  label: const Text('增加'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green.shade400,
                    foregroundColor: Colors.white,
                  ),
                ),

                OutlinedButton.icon(
                  onPressed: _resetCounter,
                  icon: const Icon(Icons.refresh),
                  label: const Text('重置'),
                ),
              ],
            ),

            const SizedBox(height: 20),

            //  弹性布局应用区域
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.grey.shade300),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '控制面板',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 12),

                  // 单选开关
                  Row(
                    children: [
                      const Text('自动模式: '),
                      Switch(value: _switchValue, onChanged: _toggleAutoMode),
                      if (_switchValue)
                        Text(
                          '(${_autoInterval}秒/次)',
                          style: TextStyle(
                            color: Colors.green.shade600,
                            fontSize: 12,
                          ),
                        ),
                    ],
                  ),

                  // 自动模式速度调节
                  if (_switchValue) ...[
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        const Text('自动速度: '),
                        Expanded(
                          child: Slider(
                            value: _autoInterval.toDouble(),
                            min: 0.5,
                            max: 5.0,
                            divisions: 9,
                            label: '${_autoInterval}秒',
                            onChanged: (value) {
                              setState(() {
                                _autoInterval = value.round();
                                // 如果自动模式正在运行，重启定时器以应用新间隔
                                if (_autoTimer != null) {
                                  _stopAutoMode();
                                  _startAutoMode();
                                }
                              });
                            },
                          ),
                        ),
                        Text('${_autoInterval}秒'),
                      ],
                    ),
                  ],

                  const SizedBox(height: 12),

                  //  输入框及表单
                  TextField(
                    controller: _textController,
                    decoration: InputDecoration(
                      labelText: '输入备注',
                      hintText: '为当前计数添加备注...',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      prefixIcon: const Icon(Icons.note_add),
                      suffixIcon: IconButton(
                        icon: const Icon(Icons.send),
                        onPressed: () {
                          if (_textController.text.isNotEmpty) {
                            setState(() {
                              _counterHistory.add(
                                '备注: ${_textController.text}',
                              );
                              _textController.clear();
                            });
                          }
                        },
                      ),
                    ),
                    onSubmitted: (value) {
                      if (value.isNotEmpty) {
                        setState(() {
                          _counterHistory.add('备注: $value');
                          _textController.clear();
                        });
                      }
                    },
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            //  ListView
            Container(
              height: 200,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey.shade300),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.purple.shade50,
                      borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(8),
                        topRight: Radius.circular(8),
                      ),
                    ),
                    child: Row(
                      children: [
                        const Icon(Icons.history, size: 16),
                        const SizedBox(width: 8),
                        Text(
                          '操作历史',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.purple.shade700,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child:
                        _counterHistory.isEmpty
                            ? const Center(
                              child: Text(
                                '暂无操作历史',
                                style: TextStyle(color: Colors.grey),
                              ),
                            )
                            : ListView.builder(
                              itemCount: _counterHistory.length,
                              reverse: true, // 最新的在顶部
                              itemBuilder: (context, index) {
                                return ListTile(
                                  dense: true,
                                  leading: CircleAvatar(
                                    radius: 12,
                                    backgroundColor: Colors.purple.shade100,
                                    child: Text(
                                      '${_counterHistory.length - index}',
                                      style: const TextStyle(fontSize: 10),
                                    ),
                                  ),
                                  title: Text(
                                    _counterHistory[_counterHistory.length -
                                        1 -
                                        index],
                                    style: const TextStyle(fontSize: 14),
                                  ),
                                );
                              },
                            ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            //  流式布局展示
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '统计信息',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                      color: Colors.blue.shade800,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Wrap(
                    //  流式布局
                    spacing: 8,
                    runSpacing: 8,
                    children: [
                      _buildInfoChip('当前计数', '$_counter', Colors.purple),
                      _buildInfoChip(
                        '操作次数',
                        '${_counterHistory.length}',
                        Colors.blue,
                      ),
                      _buildInfoChip(
                        '是否偶数',
                        _counter % 2 == 0 ? '是' : '否',
                        Colors.green,
                      ),
                      _buildInfoChip(
                        '自动模式',
                        _switchValue ? '开启(${_autoInterval}s)' : '关闭',
                        Colors.orange,
                      ),
                      _buildInfoChip(
                        '进度百分比',
                        '${(_progressValue * 100).toInt()}%',
                        Colors.red,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),

      // 悬浮按钮
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _incrementCounter,
        tooltip: '增加计数',
        icon: const Icon(Icons.add),
        label: const Text('计数+1'),
        backgroundColor: Colors.purple.shade400,
        foregroundColor: Colors.white,
      ),
    );
  }

  //  自定义信息芯片组件
  Widget _buildInfoChip(String label, String value, MaterialColor color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: color.shade100,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: color.shade300),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '$label: ',
            style: TextStyle(
              fontSize: 12,
              color: color.shade700,
              fontWeight: FontWeight.w500,
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 12,
              color: color.shade800,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
}

/*
=========== 扩展功能特色 ===========
1. 响应式布局设计，适配不同屏幕尺寸
2. 丰富的交互反馈，包括动画效果
3. 实时进度追踪和历史记录
4. 多样化的视觉样式和主题统一
5. 完整的状态管理和用户输入处理
6. 组件化设计，代码结构清晰
7. **自动模式功能**：
   - 可设置0.5-5秒的自动计数间隔
   - 实时调节自动计数速度
   - 自动模式状态记录和标记
   - 智能定时器管理，防止内存泄漏

=== 自动模式详细功能 ===
• **自动计数**：开启后按设定间隔自动增加计数
• **速度调节**：通过滑块调节0.5-5秒的计数间隔
• **实时切换**：可随时开启/关闭自动模式
• **状态追踪**：所有自动操作都会在历史记录中标记
• **资源管理**：自动清理定时器，避免内存泄漏
• **智能重启**：调节速度时自动应用新的时间间隔
*/
